function X = genImgPatches(ImgPath, Patch, hImgProcess, Schedule)

if nargin < 4
    Schedule = 'Generating image patches. Please wait ...';
end

%%
TempPath = fullfile(fileparts(ImgPath), ['%Temp-' num2str(round(rand*1e4))]);
% TempPath = fullfile(fileparts(TrainImgPath), '%Temp');
srdata.mkdirs(TempPath);

%%
% group_size = 5e3;
group_size = 5e4;

% padding = abs(x_size - y_size) / 2;
% y_stride = Patch.stride + padding;

if length(Patch.size) == 1, Patch.size = [Patch.size Patch.size]; end
if length(Patch.stride) == 1, Patch.stride = [Patch.stride Patch.stride]; end

X = zeros([Patch.size, group_size]);

ImageFiles = srimg.dirimgs(ImgPath, true);

%%
pp = 0;  count = 0;
ImgNum = length(ImageFiles);
h = waitbar(0, Schedule);
for i = 1 : ImgNum
    % fprintf('\tScale %d, Image %d/%d\n', Patch.scale, i, ImgNum);
    waitbar(i / ImgNum)
    
    x = srimg.imread(fullfile(ImgPath, ImageFiles{i}), 3); % , Patch.scale);
    % [y_bic, x] = srimg.im2lr(y, Patch.scale, 'bicubic');
    x = hImgProcess(x);
    
    x = srimg.im2colstep(x, Patch.size, Patch.stride);
    x = reshape(x, [Patch.size size(x, 2)]);
    
    len = pp(end);
    pp  = pp(end)+1 : pp(end)+size(x, 3);
    if pp(end) > group_size
        pp = 1 : size(x, 3);
        count = count + 1;
        xx = X(:, :, 1 : len);
        save(fullfile(TempPath, ['tempdata' num2str(count) '.mat']), 'i', 'xx');
    end
    
    X(:, :, pp) = x;
end
X = X(:, :, 1 : pp(end));
close(h)

%%
if count > 0
    X = srimg.MergePatches(TempPath, 'tempdata*.mat', X);
end
rmdir(TempPath, 's')
